package com.unlcn.ils.wms.backend.service.outbound.impl;

import com.google.common.collect.Lists;
import com.unlcn.ils.wms.backend.enums.HandoverSendStatusEnum;
import com.unlcn.ils.wms.backend.enums.SendBusinessFlagEnum;
import com.unlcn.ils.wms.backend.enums.SendStatusEnum;
import com.unlcn.ils.wms.backend.enums.WhCodeEnum;
import com.unlcn.ils.wms.backend.service.outbound.WmsDealerCarBackService;
import com.unlcn.ils.wms.backend.service.webservice.bo.WmsDealerCarBackResultDTO;
import com.unlcn.ils.wms.backend.service.webservice.client.WmsJmSapService;
import com.unlcn.ils.wms.backend.service.webservice.dto.ResultForDcsDealerCarbackDetailsDTO;
import com.unlcn.ils.wms.backend.service.webservice.vo.WmsDealerCarBackVO;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsDcsLogMapper;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsDealerBackExcpMapper;
import com.unlcn.ils.wms.base.mapper.outbound.WmsDealerCarBackMapper;
import com.unlcn.ils.wms.base.model.junmadcs.WmsDcsLogWithBLOBs;
import com.unlcn.ils.wms.base.model.junmadcs.WmsDealerBackExcp;
import com.unlcn.ils.wms.base.model.junmadcs.WmsDealerBackExcpExample;
import com.unlcn.ils.wms.base.model.outbound.WmsDealerCarBack;
import com.unlcn.ils.wms.base.model.outbound.WmsDealerCarBackExample;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by DELL on 2017/9/27.
 */
@Service
public class WmsDealerCarBackServiceImpl implements WmsDealerCarBackService {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Logger LOGGER = LoggerFactory.getLogger(WmsDealerCarBackServiceImpl.class);
    @Autowired
    private WmsDealerCarBackMapper wmsDealerCarBackMapper;
    @Autowired
    private WmsDcsLogMapper wmsDcsLogMapper;

    @Override
    public ArrayList<ResultForDcsDealerCarbackDetailsDTO> saveWmsDealerCarBack(WmsDealerCarBackVO[] backVOS, String s_body, String s_head) throws Exception {
        LOGGER.info("WmsDealerCarBackServiceImpl.saveWmsDealerCarBack param{}", backVOS);
        //记录日志
        Runnable runnable = () -> {
            WmsDcsLogWithBLOBs log = new WmsDcsLogWithBLOBs();
            log.setMsgBody(s_body);
            log.setMsgHead(s_head);
            log.setSendType("IN");
            log.setGmtCreate(new Date());
            log.setGmtUpdate(new Date());
            log.setUrl("WmsDealerCarBackServiceImpl.saveWmsDealerCarBack");
            wmsDcsLogMapper.insertSelective(log);
            LOGGER.info("WmsDealerCarBackServiceImpl.saveWmsDealerCarBack  保存退车数据成功");
        };
        new Thread(runnable).start();

        ArrayList<ResultForDcsDealerCarbackDetailsDTO> detailsDTO = Lists.newArrayList();
        for (WmsDealerCarBackVO backVO : backVOS) {
            ResultForDcsDealerCarbackDetailsDTO detail = new ResultForDcsDealerCarbackDetailsDTO();
            //校验字段
            WmsDealerCarBackResultDTO wmsDealerCarBackResultDTO = checkWmsDealerCarBack(backVO);
            WmsDealerCarBack wmsDealerCarBack = new WmsDealerCarBack();
            BeanUtils.copyProperties(backVO, wmsDealerCarBack);
            if (Objects.isNull(wmsDealerCarBackResultDTO)) {
                //非空验证通过
                //格式校验
                if (StringUtils.isNotBlank(backVO.getCbCarBackTime())) {
                    try {
                        Date parse = sdf.parse(backVO.getCbCarBackTime());
                        wmsDealerCarBack.setCbCarBackTime(parse);
                    } catch (ParseException e) {
                        LOGGER.error("WmsDealerCarBackServiceImpl.saveWmsDealerCarBack param{}", e);
                        //明细
                        detail.seteMsg("退车时间格式不正确:yyyy-MM-dd HH:mm:ss");
                        detail.setCbVin(backVO.getCbVin());
                        detailsDTO.add(detail);
                        //return detailsDTO;
                        //throw new BusinessException("退车时间格式不正确:yyyy-MM-dd HH:mm:ss");
                    }
                }
                if (CollectionUtils.isEmpty(detailsDTO)) {
                    //格式通过
                    //重复校验
                    WmsDealerCarBackExample backExample = new WmsDealerCarBackExample();
                    backExample.createCriteria().andCbVinEqualTo(wmsDealerCarBack.getCbVin()).andCbZstatusNotEqualTo(HandoverSendStatusEnum.SEND_SUCCESS.getStatusCode());
                    List<WmsDealerCarBack> wmsDealerCarBacks = wmsDealerCarBackMapper.selectByExample(backExample);
                    if (CollectionUtils.isNotEmpty(wmsDealerCarBacks)) {
                        //说明已经存在;
                        //明细
                        detail.seteMsg("车架号:" + wmsDealerCarBack.getCbVin() + "已经在WMS进行了退车!");
                        detail.setCbVin(backVO.getCbVin());
                        detailsDTO.add(detail);
                        //return detailsDTO;
                        //throw new BusinessException("车架号:" + wmsDealerCarBack.getCbVin() + "已经在WMS进行了退车!");
                    }
                }
                if (CollectionUtils.isEmpty(detailsDTO)) {
                    try {
                        wmsDealerCarBack.setCbZstatus(HandoverSendStatusEnum.NO_SEND.getStatusCode());
                        wmsDealerCarBack.setGmtCreate(new Date());
                        wmsDealerCarBack.setGmtUpdate(new Date());
                        if (wmsDealerCarBack.getCbWhName().contains("CS")) {
                            wmsDealerCarBack.setCbLgort(wmsDealerCarBack.getCbWhName());
                            wmsDealerCarBack.setCbWhName(WhCodeEnum.JM_CS.getText());
                            wmsDealerCarBack.setCbWhCode(WhCodeEnum.JM_CS.getValue());
                        }

                        if (wmsDealerCarBack.getCbWhName().contains("XY")) {
                            wmsDealerCarBack.setCbLgort(wmsDealerCarBack.getCbWhName());
                            wmsDealerCarBack.setCbWhCode(WhCodeEnum.JM_XY.getValue());
                            wmsDealerCarBack.setCbWhName(WhCodeEnum.JM_XY.getText());
                        }
                        wmsDealerCarBack.setCbSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()));
                        wmsDealerCarBack.setCbReceiveTime(new Date());
                        wmsDealerCarBackMapper.insert(wmsDealerCarBack);
                    } catch (Exception ex) {
                        LOGGER.error("WmsDealerCarBackServiceImpl.saveWmsDealerCarBack param{}", ex);
                        //明细
                        detail.seteMsg("车架号:" + wmsDealerCarBack.getCbVin() + "申请发送异常!请再次发送");
                        detail.setCbVin(backVO.getCbVin());
                        detailsDTO.add(detail);
                        //throw new BusinessException("经销商退车申请发送异常!请再次发送");
                    }
                }

            } else {//验证不过
                //明细
                detail.seteMsg(wmsDealerCarBackResultDTO.geteMsg());
                detail.setCbVin(backVO.getCbVin());
                detailsDTO.add(detail);
                //return detailsDTO;
                //throw new BusinessException(wmsDealerCarBackResultDTO.geteMsg());
            }
        }
        return detailsDTO;
    }

    /**
     * 根据车架号获取退车信息
     *
     * @param vin
     * @return
     * @throws Exception
     */
    @Override
    public WmsDealerCarBack getWmsDealerCarBackByVin(String vin) throws Exception {
        LOGGER.error("WmsDealerCarBackServiceImpl.getWmsDealerCarBackByVin vin{}", vin);
        if (StringUtils.isNotBlank(vin)) {
            WmsDealerCarBackExample example = new WmsDealerCarBackExample();
            example.createCriteria().andCbVinEqualTo(vin);
            List<WmsDealerCarBack> dealerCarBackList = wmsDealerCarBackMapper.selectByExample(example);
            if (CollectionUtils.isNotEmpty(dealerCarBackList)) {
                return dealerCarBackList.get(0);
            }
        }
        return null;
    }

    @Autowired
    private WmsJmSapService wmsJmSapService;

    @Autowired
    private WmsDealerBackExcpMapper wmsDealerBackExcpMapper;

    private static final int TOTAL_COUNT = 5;

    /**
     * 退车申请接口 调用sap
     *
     * @throws Exception
     */
    @Override
    public void updateDelearCarBack() throws Exception {
        LOGGER.info("WmsDealerCarBackServiceImpl.updateDelearCarBack param{}");
        WmsDealerCarBackExample backExample = new WmsDealerCarBackExample();
        backExample.or().andCbZstatusEqualTo(SendStatusEnum.SEND_INIT.getValue());
        backExample.or().andCbZstatusIsNull();
        backExample.setOrderByClause(" cb_id DESC ");
        backExample.setLimitStart(0);
        backExample.setLimitEnd(1);
        List<WmsDealerCarBack> wmsDealerCarBacks = wmsDealerCarBackMapper.selectByExample(backExample);
        if (CollectionUtils.isNotEmpty(wmsDealerCarBacks)) {
            wmsJmSapService.updateWmsDealerCarBack(wmsDealerCarBacks);
        }
    }


    /**
     * 退车申请接口 调用sap
     *
     * @throws Exception
     */
    @Override
    public void updateDelearCarBackExcp() throws Exception {
        LOGGER.info("WmsDealerCarBackServiceImpl.updateDelearCarBackExcp param{}");
        //查询异常表
        WmsDealerBackExcpExample excpExample = new WmsDealerBackExcpExample();
        excpExample.createCriteria().andCbZstatusEqualTo(SendStatusEnum.SEND_FAILED.getValue())
                .andFinalStatusIsNull();
        excpExample.setOrderByClause(" data_id DESC ");
        excpExample.setLimitStart(0);
        excpExample.setLimitEnd(1);
        List<WmsDealerBackExcp> wmsDealerBackExcps = wmsDealerBackExcpMapper.selectByExample(excpExample);
        if (CollectionUtils.isNotEmpty(wmsDealerBackExcps)) {
            WmsDealerBackExcp wmsDealerBackExcp = wmsDealerBackExcps.get(0);
            if (wmsDealerBackExcp != null && StringUtils.isNotBlank(wmsDealerBackExcp.getCbZstatus())) {
                if (wmsDealerBackExcp.getCbZstatus().equals(SendStatusEnum.SEND_FAILED.getValue())) {
                    WmsDealerCarBack wmsDealerCarBack = new WmsDealerCarBack();
                    ArrayList<WmsDealerCarBack> list = Lists.newArrayList();
                    BeanUtils.copyProperties(wmsDealerBackExcp, wmsDealerCarBack);
                    list.add(wmsDealerCarBack);
                    wmsJmSapService.updateWmsDealerCarBack(list);
                }
            }
        }
    }


    /**
     * 经销商退车的数据验证，只非空验证
     *
     * @param backVO
     * @return
     */
    private WmsDealerCarBackResultDTO checkWmsDealerCarBack(WmsDealerCarBackVO backVO) {
        StringBuffer eMsg = new StringBuffer();
        if (StringUtils.isBlank(backVO.getCbApplyNo())) {
            eMsg.append("退车申请单号为空；");
        }
        if (StringUtils.isBlank(backVO.getCbLineId())) {
            eMsg.append("行ID为空!");
        }
        if (StringUtils.isBlank(backVO.getCbDealerCode())) {
            eMsg.append("经销商代码为空；");
        }
        //if (StringUtils.isBlank(backVO.getCbDealerName())) {
        //    eMsg.append("经销商名称为空；");
        //}
        //if (StringUtils.isBlank(backVO.getCbMaterialCode())) {
        //    eMsg.append("物料代码为空；");
        //}
        //if (StringUtils.isBlank(backVO.getCbMaterialName())) {
        //    eMsg.append("物料名称为空；");
        //}
        if (StringUtils.isBlank(backVO.getCbVin())) {
            eMsg.append("车架号为空；");
        }
        if (StringUtils.isBlank(backVO.getCbWhName())) {
            eMsg.append("退车仓库为空；");
        }
        //if (backVO.getCbCarBackTime() == null) {
        //    eMsg.append("退车时间为空；");
        //}

        if (eMsg.length() > 0) {
            WmsDealerCarBackResultDTO wmsDealerCarBackResultDTO = new WmsDealerCarBackResultDTO();
            wmsDealerCarBackResultDTO.setCbVin(backVO.getCbVin());
            wmsDealerCarBackResultDTO.seteMsg(eMsg.toString());
            return wmsDealerCarBackResultDTO;
        } else {
            return null;
        }
    }
}
